package com.itcoon.transform.base.register.unannotated;

import com.itcoon.transform.base.definition.ModelDefinition;
import com.itcoon.transform.base.definition.ModelPropertyDefinition;
import com.itcoon.transform.base.utils.TransformServiceUtils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

public class UnAnnotatedClazzAssembleModelRegister implements UnAnnotedAssembleModelRegister{
    @Override
    public boolean support(Class<?> targetClass) {
        return !targetClass.isInterface();
    }

    @Override
    public void register(ModelDefinition modelDefinition) throws IntrospectionException{
        Class<?> targetClass = modelDefinition.getTargetClass();
        BeanInfo targetBeanInfo = Introspector.getBeanInfo(targetClass);
        PropertyDescriptor[] targetPropertyDescriptors = targetBeanInfo.getPropertyDescriptors();
        for (PropertyDescriptor targetPropertyDescriptor : targetPropertyDescriptors) {
            if (targetPropertyDescriptor.getName().equals("class")) {
                continue;
            }
            ModelPropertyDefinition mpd = new ModelPropertyDefinition(modelDefinition);
            mpd.setAnnotated(false);
            mpd.setTargetGetter(targetPropertyDescriptor.getReadMethod());
            mpd.setTargetAttribute(targetPropertyDescriptor.getName());
            mpd.setTargetPropertyType(targetPropertyDescriptor.getPropertyType());

            mpd.setTargetSetter(targetPropertyDescriptor.getWriteMethod());
            mpd.setOriginAttribute(mpd.getTargetAttribute());

            //如果目标类没有setter，则跳到下一个
            if (mpd.getTargetSetter() == null) {
                modelDefinition.getPropertyDefinitions().add(mpd);
                continue;
            }

            Method originGetter = TransformServiceUtils.findGetterFromValue(modelDefinition.getOriginClass(), mpd.getOriginAttribute());
            if(originGetter == null){
                continue;
            }
            mpd.setOriginGetter(originGetter);
            Class<?> originPropertyType = originGetter.getReturnType();
            mpd.setOriginPropertyType(originPropertyType);
            modelDefinition.getPropertyDefinitions().add(mpd);
        }
    }
}
